package com.admin.zhou.controller.admin;

import com.admin.zhou.common.Const;
import com.admin.zhou.common.ServerResponse;
import com.admin.zhou.model.TRights;
import com.admin.zhou.model.TAdminUser;
import com.admin.zhou.model.TRoles;
import com.admin.zhou.redis.RedisUtil;
import com.admin.zhou.service.TAdminUserService;
import com.admin.zhou.utils.RSAUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.xdevapi.JsonArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


@RestController
@RequestMapping("/api")
public class AdminerController {

    private Logger logger = LoggerFactory.getLogger(AdminerController.class);

    @Autowired
    private TAdminUserService tAdminUserService;

    @Autowired
    private RedisUtil redisUtil;



    @PostMapping("/userLogin")
    public ServerResponse userLogin(@RequestBody HashMap<String,String> mapReq) throws Exception {


        String account = mapReq.get("username");
        String password = mapReq.get("password");

        if(StringUtils.isEmpty(account) || StringUtils.isEmpty(password)){
            return ServerResponse.createByErrorMessage("数据错误");
        }

        TAdminUser user = tAdminUserService.getAdminUserByAcount(account);

        if(user == null || !user.getPassword().equals(password)){
            return ServerResponse.createByErrorMessage("账号或者密码错误");
        }


        JSONObject object = new JSONObject();
        object.put("name", user.getName());
        Date newTime = new Date();
        tAdminUserService.updateRecentlyLanded(user.getId(),newTime);
        String res = user.getId()+"-"+newTime.getTime();
        String encrypt = RSAUtils.encryptByPubKey(res,RSAUtils.PUBLIC_KEY);
        redisUtil.set(Const.REDIS_ADMIN+user.getId(),encrypt,60*60);

        object.put("token",encrypt);

        return ServerResponse.createBySuccess("登录成功",object);

    }

    @GetMapping("/getMenus")
    public ServerResponse getMenus() throws Exception {

        ArrayList<TRights> menuList = new ArrayList<>();
        List<TRights> list = tAdminUserService.getRights();

        for (TRights menu: list){
            if(menu.getPid() == 0){
                menuList.add(menu);
                if(menu.getChildren() == null){
                    menu.setChildren(new ArrayList<>());
                }
                for (TRights child: list){
                    if(child.getPid() == menu.getId()){
                        menu.getChildren().add(child);
                    }
                }
            }
        }
        return ServerResponse.createBySuccess("获取菜单列表成功",menuList);
    }


    /**
     * 获取用户列表
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/getUserList")
    public ServerResponse getUserList(String query,
                                      @RequestParam(value = "page") Integer page,
                                         @RequestParam(value = "pageSize") Integer pageSize){

        if(page <= 0 || pageSize <= 0 ){
            return ServerResponse.createByErrorMessage("参数错误");
        }

        if(StringUtils.isEmpty(query)){
            query = "";
        }


        int total = tAdminUserService.getUserToalNumber(query);

        int start = (page-1)*pageSize;
        List<TAdminUser> list = tAdminUserService.getUserList(query,start,pageSize);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total",total);
        jsonObject.put("pageNum",page);
        if(list != null){
            JSONArray array = new JSONArray();
            for(TAdminUser item: list){
                JSONObject itemObject = new JSONObject();
                itemObject.put("id",item.getId());
                itemObject.put("name",item.getName());
                itemObject.put("mobile",item.getMobile());
                itemObject.put("u_state",item.getState());
                itemObject.put("createTime",item.getCreateTime().getTime());
                itemObject.put("role_id",item.getRole_id());

                TRoles role = tAdminUserService.getRoleById(item.getRole_id());
                itemObject.put("role_name",role == null?"未分配":role.getRoleName());
                array.add(itemObject);
            }
            jsonObject.put("users",array);
        }

        return ServerResponse.createBySuccess(jsonObject);

    }

    /**
     * 更新用户状态
     * @return
     */
    @GetMapping("/updateUserState")
    public ServerResponse updateUserState(@RequestParam(value = "state") Integer state, HttpServletRequest request){

        if(state != 0 && state != 1){
            return ServerResponse.createByErrorMessage("参数错误");
        }

        String idstr = (String) request.getAttribute(Const.CURRENT_USER);
        long userid = Long.parseLong(idstr);

        int number = tAdminUserService.updateUserState(state,userid);

        if(number > 0){
            return ServerResponse.createBySuccess();
        }else{
            return ServerResponse.createByError();
        }
    }

    /**
     * 添加用户
     * @param mapReq
     * @return
     * @throws Exception
     */
    @PostMapping("/addUser")
    public ServerResponse addUser(@RequestBody HashMap<String,String> mapReq) throws Exception {


        String account = mapReq.get("username");
        String password = mapReq.get("password");
        String name = mapReq.get("name");
        String phone = mapReq.get("phone");


        if(StringUtils.isEmpty(account)
                || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(name)
                || StringUtils.isEmpty(phone)){
            return ServerResponse.createByErrorMessage("参数错误");
        }

        if(tAdminUserService.getAdminUserByAcount(account) != null){
            return ServerResponse.createByErrorMessage("账号已存在");
        }

        TAdminUser user = new TAdminUser();
        user.setName(name);
        user.setAccount(account);
        user.setPassword(password);
        user.setMobile(phone);
        user.setRole_id(0L);
        user.setCreateTime(new Date());

        tAdminUserService.addUser(user);

        if(user.getId() == null){
            return ServerResponse.createByErrorMessage("用户添加失败");
        }

        return ServerResponse.createBySuccessMessage("用户添加成功");

    }

    @GetMapping("/getUser/{id}")
    public ServerResponse getUserById(@PathVariable("id") Long id){

        TAdminUser user = tAdminUserService.getAdminUserById(id);
        if(user == null){
            return ServerResponse.createByErrorMessage("获取失败");
        }

        JSONObject object  = new JSONObject();
        object.put("id",user.getId());
        object.put("name",user.getName());
        object.put("username",user.getAccount());
        object.put("mobile",user.getMobile());

        return ServerResponse.createBySuccess(object);
    }


    /**
     * 修改用户
     * @param mapReq
     * @return
     * @throws Exception
     */
    @PostMapping("/editUser/{id}")
    public ServerResponse editUser(@PathVariable("id") Long id,@RequestBody HashMap<String,String> mapReq) throws Exception {

        String name = mapReq.get("name");
        String mobile = mapReq.get("mobile");


        if(StringUtils.isEmpty(name) || StringUtils.isEmpty(mobile)){
            return ServerResponse.createByErrorMessage("参数错误");
        }

        int number = tAdminUserService.updateUser(id,name,mobile);

        if(number == 0){
            return ServerResponse.createByErrorMessage("用户修改失败");
        }

        return ServerResponse.createBySuccessMessage("用户修改成功");

    }

    /**
     * 删除用户
     * @return
     * @throws Exception
     */
    @GetMapping("/deleteUser/{id}")
    public ServerResponse deleteUser(@PathVariable("id") Long id) throws Exception {

        int number = tAdminUserService.deleteUserById(id);

        if(number == 0){
            return ServerResponse.createByErrorMessage("删除失败");
        }

        return ServerResponse.createBySuccessMessage("用户删除成功");

    }

    /**
     * 分配用户角色
     * @return
     * @throws Exception
     */
    @PutMapping("/users/{id}/role/{roleId}")
    public ServerResponse setUserRole(@PathVariable("id") String id,@PathVariable("roleId") String roleId) throws Exception {


        long id1 = Long.parseLong(roleId);
        long id2 = Long.parseLong(id);

        int number = tAdminUserService.updateUserRole(id1,id2);

        if(number > 0){
            return ServerResponse.createBySuccessMessage("分配角色成功");
        }

        return ServerResponse.createByErrorMessage("数据异常");

    }


    /**
     *
     * @param type  list和tree
     * @return
     * @throws Exception
     */
    @GetMapping("/rights/{type}")
    public ServerResponse rights(@PathVariable("type") String type) throws Exception {

        List<TRights> list = tAdminUserService.getRights();
        if("list".equals(type)){
            return ServerResponse.createBySuccess("获取菜单列表成功",list);
        }else if ("tree".equals(type)){
            ArrayList<TRights> parentList = new ArrayList<>();
            for (TRights right: list){
                if(right.getLevel() == 0){
                    parentList.add(right);
                }
            }
            recursionChildren(parentList,list);
            return ServerResponse.createBySuccess(parentList);
        }

        return ServerResponse.createByErrorMessage("请求错误");
    }




    /**
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/roles")
    public ServerResponse roles() throws Exception {


        List<TRoles> list = tAdminUserService.getRoles();

        JSONArray roleArray = new JSONArray();
        for (TRoles role: list){
            JSONObject object = new JSONObject();
            object.put("id",role.getId());
            object.put("roleName",role.getRoleName());
            object.put("des",role.getRoleDescribe());
            List<TRights> rights = tAdminUserService.getRightsByRoleId(role.getId());

            ArrayList<TRights> parentList = new ArrayList<>();
            for (TRights right: rights){
                if(right.getLevel() == 0){
                    parentList .add(right);
                }
            }
            recursionChildren(parentList,rights);
            object.put("children",parentList);
            roleArray.add(object);
        }

        return ServerResponse.createBySuccess("获取角色列表成功",roleArray);
    }

    // 递归获取子节点数据
    public static void recursionChildren (List<TRights> parentList, List<TRights> allList) {
        for (TRights parent : parentList) {
            List<TRights> childrenList = null;
            for (TRights all : allList) {
                if (all.getPid() == parent.getId()) {
                    if(childrenList == null) childrenList = new ArrayList<>();
                    childrenList.add(all);
                }
            }
            parent.setChildren(childrenList);
            if (parent.getLevel() <= 1 && childrenList != null) {
                recursionChildren(childrenList, allList);
            }
        }
    }

    /**
     *
     * @return
     * @throws Exception
     */
    @DeleteMapping("/roles/{roleid}/rights/{rightid}")
    public ServerResponse rights(@PathVariable("roleid") String roleid,@PathVariable("rightid") String rightid) throws Exception {


        long role_id_long = Long.parseLong(roleid);
        long right_id_long = Long.parseLong(rightid);

        List<Long> idList = tAdminUserService.getRightsByIdOrPid(right_id_long);

        if(idList == null){
            return ServerResponse.createByErrorMessage("权限不存在");
        }

        String ids = "";
        for (Long id: idList){
            ids += ","+id;
        }
        ids = ids.substring(1);

        tAdminUserService.deleteRightsByIds(ids,role_id_long);

        List<TRights> rights = tAdminUserService.getRightsByRoleId(role_id_long);

        ArrayList<TRights> parentList = new ArrayList<>();
        for (TRights right: rights){
            if(right.getLevel() == 0){
                parentList.add(right);
            }
        }
        recursionChildren(parentList,rights);

        return ServerResponse.createBySuccess(parentList);
    }



    /**
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/roles/{roleid}/rights")
    public ServerResponse setRights(@PathVariable("roleid") String roleid,@RequestBody HashMap<String,String> mapReq) throws Exception {


        long role_id_long = Long.parseLong(roleid);

        String idStr = mapReq.get("ids");

        if(StringUtils.isEmpty(idStr)){
            return ServerResponse.createByErrorMessage("数据错误");
        }

        List<String> ids = Arrays.asList(idStr.split(","));
        tAdminUserService.insertRightsToRole(ids,role_id_long);


        return ServerResponse.createBySuccessMessage("分配成功");
    }



    @GetMapping("/getRoles")
    public ServerResponse getRoles() throws Exception {


        List<TRoles> list = tAdminUserService.getRoles();

        return ServerResponse.createBySuccess(list);
    }

    /**
     * 添加角色
     * @param mapReq
     * @return
     * @throws Exception
     */
    @PostMapping("/addOrEditRole")
    public ServerResponse addOrEditRole(@RequestBody HashMap<String,String> mapReq) throws Exception {

        String idStr = mapReq.get("id");
        String roleName = mapReq.get("roleName");
        String roleDes = mapReq.get("roleDes");


        if(StringUtils.isEmpty(roleName) || StringUtils.isEmpty(roleDes)){
            return ServerResponse.createByErrorMessage("参数错误");
        }

        if(StringUtils.isEmpty(idStr)){
            TRoles role = new TRoles();
            role.setRoleName(roleName);
            role.setRoleDescribe(roleDes);
            tAdminUserService.addRole(role);
            return ServerResponse.createBySuccessMessage("角色创建成功");
        }

        Long id = Long.parseLong(idStr);

        int number = tAdminUserService.updateRoleInfoById(id,roleName,roleDes);

        if(number > 0){
            return ServerResponse.createBySuccessMessage("角色更新成功");
        }


        return ServerResponse.createByErrorMessage("角色更新失败");

    }

    /**
     * 删除角色
     * @return
     * @throws Exception
     */
    @GetMapping("/deleteRole/{id}")
    public ServerResponse deleteRole(@PathVariable("id") Long id) throws Exception {

        int number = tAdminUserService.deleteRoleById(id);

        if(number == 0){
            return ServerResponse.createByErrorMessage("角色删除失败");
        }

        return ServerResponse.createBySuccessMessage("角色删除成功");

    }
}
